import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:wheel_of_fortune/candy/candy_page.dart';
import 'package:wheel_of_fortune/candy/candy_win_page.dart';
import 'package:wheel_of_fortune/model/rotary_table_model.dart';
import 'package:wheel_of_fortune/provider/wheel_of_fortune_provider.dart';
import 'package:wheel_of_fortune/rules_page.dart';
import 'package:wheel_of_fortune/utils/utils.dart';
import 'package:wheel_of_fortune/widgets/no_candy.dart';
import 'package:wheel_of_fortune/widgets/no_spins.dart';
import 'package:wheel_of_fortune/widgets/provider_widget.dart';
import 'package:wheel_of_fortune/widgets/redeem_spin.dart';
import 'package:wheel_of_fortune/widgets/share_widget.dart';
import 'package:wheel_of_fortune/widgets/spin_button.dart';
import 'package:wheel_of_fortune/widgets/topup.dart';
import 'dart:math';

import 'complete_page.dart';
import 'money/money_win_page.dart';
import 'product/product_win_page.dart';
import 'widgets/candy_exchange.dart';
import 'widgets/customer_button.dart';
import 'widgets/fortune_wheel_dialog.dart';
import 'widgets/message_alerts.dart';
import 'widgets/remaining.dart';

class WheelOfFortunePage extends StatefulWidget {
  WheelOfFortunePage({Key key}) : super(key: key);

  @override
  _WheelOfFortunePageState createState() => _WheelOfFortunePageState();
}

class _WheelOfFortunePageState extends State<WheelOfFortunePage>
    with SingleTickerProviderStateMixin {
  WheelOfFortuneProvider _provider;
  bool _isComplete = false;

  Animation<double> tween;
  AnimationController controller;
  bool _isAnimating = false;
  // 赢得的奖品
  var winPrize;
  int rewardIndex = 0;
  var _statusListener;
  List list = [
    'Money 100',
    'Candy 100',
    'iPhone 11',
    'Candy 50',
    'Money 100',
    'Candy 100',
    'Money 500',
    'Candy 50',
  ];
  @override
  void initState() {
    super.initState(); 
    //控制类对象
    controller = new AnimationController(
      duration: const Duration(seconds: 3),
      vsync: this,
    );
  }

  /// Spin旋转
  void _spin() async {
    // 有次数直接转
    if (_provider.model.residueLotteryCount > 0) {
      _statusListener = (AnimationStatus status) {
        print('$status');
        if (status == AnimationStatus.completed) {
          _isAnimating = false;
          tween.removeStatusListener(_statusListener);
        }
      };
      //补间动画
      tween = Tween<double>(
        begin: 0.0,
        end: pi * 2 * 3,
      ).animate(
        CurvedAnimation(
          parent: controller,
          curve: Interval(
            0.0,
            1.0,
            curve: Curves.easeIn,
          ),
        ),
      )
        ..addListener(() {
          setState(() {});
        })
        ..addStatusListener(_statusListener);
      controller.reset();
      controller.forward();
      controller.repeat(period: Duration(seconds: 1));
      _isAnimating = true;
      await Future.delayed(Duration(seconds: 2));
      winPrize = await _provider?.getAward();
      int prizeId = winPrize['prizeId'] ?? 13;
      rewardIndex = _provider?.model?.prizeInfos
          ?.indexWhere((element) => element.id == prizeId);
      print('rewardIndex = $rewardIndex');
      _provider?.model?.residueLotteryCount--;
      controller.stop();
      double rewardAngle = pi / 180.0 * (270 - (rewardIndex * 1.0 / 8) * 360.0);
      print('rewardAngle = $rewardAngle');
      //补间动画
      tween = Tween<double>(
        begin: 0.0,
        end: pi * 2 * 3 + rewardAngle,
      ).animate(
        CurvedAnimation(
          parent: controller,
          curve: Interval(
            0.0,
            1.0,
            curve: Curves.easeInOut,
          ),
        ),
      )
        ..addListener(() {
          setState(() {});
        })
        ..addStatusListener(_statusListener);
      controller.reset();
      controller.forward();
      _isAnimating = true;
      PrizeInfos prizeInfos = _provider.model.prizeInfos[rewardIndex];
      
      bool back = await showModalBottomSheet(
        context: context,
        enableDrag: false,
        isScrollControlled: true,
        backgroundColor: Colors.transparent,
        builder: (c) {
          return AlertDialog(
            backgroundColor: Colors.transparent,
            shape: RoundedRectangleBorder(
              side: BorderSide.none,
              borderRadius:
                  BorderRadius.all(Radius.circular(13)),
            ),
            titlePadding: EdgeInsets.fromLTRB(0, 0, 0, 0),
            title: prizeInfos.type == 'NOTHING'?NothingDialog():GetPrizeDialog(prizeInfos, winPrize['lotteryId']),
          );
        },
      );
      if (back) _getPrize();
    } else {
      // 没有次数了，看能不能购买或者用Candy兑换
      if (_provider.model.topUpPresented) {
        _topUp();
      }
      _noSpins();
      
    }
  }
  _noSpins()async{
    await showModalBottomSheet(
      context: context,
      enableDrag: false,
      isScrollControlled: true,
      backgroundColor: Colors.transparent,
      builder: (c) {
        return AlertDialog(
          titlePadding: EdgeInsets.zero,
          title: NoSpins(
            rotaryTableId: _provider.model.rotaryTableId,
            candyExchangeAmount: _provider.model.candyExchangeAmount,
          ),
        );
      },
    );
  }


  _getPrize() async {
    PrizeInfos prizeInfos = _provider.model.prizeInfos[rewardIndex];
    if (prizeInfos.type == 'NOTHING') return;
    switch (prizeInfos.type) {
      case 'NOTHING':
        return;
        break;
      case 'ENTITY': // 得到实体产品
        {
          await Navigator.push(context, MaterialPageRoute(
            builder: (c) {
              return ProductWinPage(prizeInfos, winPrize['lotteryId']);
            },
          ));
        }
        break;
      case 'CANDY':
        {
          final re = await _provider.collectPrize(winPrize['lotteryId']);
          if(re =='success') showToast(msg: 'XX candies has been deposited to you candy box');
        }
        break;
      case 'CASH':
        {
          final re = await _provider.collectPrize(winPrize['lotteryId']);
          if(re =='success') showToast(msg: 'XX pesoes has been deposited to you wallet');
        }
        break;
      default:
    }
    winPrize = null;
    tween = null;
    _provider?.initData();
  }

  _candyExchange() async {
    if (_provider.candyBalance.toInt() > 10 && _provider.model.candyExchange) {
    // if (_provider.candyBalance.toInt() > 10) {
      await showModalBottomSheet(
        context: context,
        enableDrag: false,
        isScrollControlled: true,
        backgroundColor: Colors.transparent,
        builder: (c) {
          return AlertDialog(
            titlePadding: EdgeInsets.zero,
            title: NoCandy(
              rotaryTableId: _provider.model.rotaryTableId,
              candyExchangeAmount: _provider.model.candyExchangeAmount,
            ),
          );
        },
      );
      _provider?.initData();
    } else {
      bool back = await showModalBottomSheet(
        context: context,
        enableDrag: false,
        isScrollControlled: true,
        backgroundColor: Colors.transparent,
        builder: (c) {
          return AlertDialog(
            titlePadding: EdgeInsets.zero,
            title: CandyExchange(
              rotaryTableId: _provider.model.rotaryTableId,
              balance: _provider.candyBalance.toInt(),
              candyExchangeAmount: _provider.model.candyExchangeAmount,
            ),
          );
        },
      );
      if (back) {
        _provider?.initData();
      }
    }
  }
  _topUp() async {
    bool back = await showModalBottomSheet(
      context: context,
      enableDrag: false,
      isScrollControlled: true,
      backgroundColor: Colors.transparent,
      builder: (c) {
        return AlertDialog(
          titlePadding: EdgeInsets.zero,
          title: Topup(
            rotaryTableId: _provider.model.rotaryTableId,
            topUpAmount: _provider.model.topUpAmount,
          ),
        );
      },
    );
    if (back) {
      _provider?.initData();
    }
  }

  @override
  Widget build(BuildContext context) {
    final size = MediaQuery.of(context).size;
    final width = size.width;
    return Container(
      child: Scaffold(
        resizeToAvoidBottomPadding: false,
        appBar: AppBar(
          title: Text(
            'Wheel of Fortune',
            style: TextStyle(
              color: Colors.white,
              fontSize: 15,
              fontWeight: FontWeight.w400,
            ),
          ),
          centerTitle: true,
        ),
        body: ProviderWidget<WheelOfFortuneProvider>(
          model: WheelOfFortuneProvider(),
          onModelReady: (p) => p.initData(),
          builder: (c, provider, child) {
            _provider = provider;
            if (provider.model == null) {
              return Container(
                color: whiteColor,
                child: Center(
                  child: CircularProgressIndicator(),
                ),
              );
            }
            final spinTime = DateTimeHelper.getSpinTime(
                _provider.model?.startDate,
                _provider.model?.endDate,
                _provider.model?.startTime,
                _provider.model?.endTime);
            _isComplete = false;
            return _isComplete
                ? CompletePage()
                : SingleChildScrollView(
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Padding(
                          padding: EdgeInsets.fromLTRB(20, 20, 20, 6),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              ColorButton(
                                title: 'Rules',
                                onTap: () {
                                  showModalBottomSheet(
                                      enableDrag: false,
                                      isScrollControlled: true,
                                      backgroundColor: Colors.transparent,
                                      context: context,
                                      builder: (c) {
                                        return RulesPage();
                                      });
                                },
                              ),
                              ColorButton(
                                title: 'Share',
                                onTap: () {
                                  // Navigator.push(context, MaterialPageRoute(
                                  //   builder: (c,){
                                  //     return ProductWinPage(PrizeInfos(), 'ffefef');
                                  //   }
                                  // ));
                                  // return;
                                  showModalBottomSheet(
                                    context: context,
                                    enableDrag: false,
                                    isScrollControlled: true,
                                    backgroundColor: Colors.transparent,
                                    builder: (c) {
                                      return ShareWidget(
                                        callBack: (i) {
                                          
                                        },
                                      );
                                    },
                                  );
                                },
                              ),
                            ],
                          ),
                        ),
                        // Free Gift
                        Padding(
                          padding: EdgeInsets.only(
                            top: 0,
                          ),
                          child: Text(
                            'Free Gift',
                            style: TextStyle(
                                color: Color(0xFFFFCC00),
                                fontSize: 24,
                                fontFamily: 'Avenir Next LT Pro',
                                fontWeight: FontWeight.bold),
                          ),
                        ),
                        //Wheel of Fortune
                        Padding(
                          padding: EdgeInsets.only(
                            top: 5,
                          ),
                          child: Text(
                            'Wheel of Fortune',
                            style: TextStyle(
                                color: Color(0xFF041D57),
                                fontSize: 29,
                                fontFamily: 'Gotham'),
                          ),
                        ),
                        // Spin the wheel and earn free gift form Fortune Pay!
                        Padding(
                          padding: EdgeInsets.only(
                            top: 5,
                          ),
                          child: Text(
                            'Spin the wheel and earn free gift form Fortune Pay!\nTop-up your wallet more than Php500\nto get one more spin.',
                            textAlign: TextAlign.center,
                            style: TextStyle(
                                color: Color(0xFF3A3A3A),
                                fontSize: 12,
                                fontFamily: 'Avenir Next LT Pro'),
                          ),
                        ),
                        InkWell(
                          onTap: (!_isAnimating && winPrize != null)
                              ? _getPrize
                              : null,
                          child: Container(
                            height: width - 26,
                            padding: EdgeInsets.only(
                              top: 12,
                            ),
                            child: Stack(
                              overflow: Overflow.visible,
                              children: <Widget>[
                                Positioned(
                                  left: -(776 - width) / 2,
                                  width: 776,
                                  height: width - 26,
                                  child: Image.asset(
                                    'assets/images/wheel_bg.png',
                                  ),
                                ),
                                Positioned(
                                  left: 13,
                                  right: 13,
                                  height: width - 26,
                                  child: Image.asset(
                                    'assets/images/ellipses.png',
                                  ),
                                ),
                                Positioned(
                                  left: 20,
                                  right: 20,
                                  top: 4,
                                  height: width - 40,
                                  child: Image.asset(
                                    'assets/images/round_fortune_wheel.png',
                                  ),
                                ),
                                Positioned(
                                  top: 40,
                                  left: 56,
                                  right: 56,
                                  height: width - 112,
                                  child: Transform.rotate(
                                    angle: tween != null ? tween.value : -1.16,
                                    child: Stack(
                                      alignment: Alignment.center,
                                      children: <Widget>[
                                        // Container(),
                                        //转盘背景
                                        Image.asset(
                                          'assets/images/fortune_wheel.png',
                                        ),
                                        Align(
                                          alignment: Alignment.center,
                                          child: SvgPicture.asset(
                                            'assets/svg/wheel_center.svg',
                                          ),
                                        ),
                                        //转盘奖励内容
                                        // Stack(
                                        //   children: getItemWidgets(),
                                        // ),
                                      ],
                                    ),
                                  ),
                                ),
                                Align(
                                  alignment: Alignment.topCenter,
                                  child: Image.asset(
                                    'assets/images/fortune_wheel_select.png',
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ),
                        Padding(
                          padding: EdgeInsets.only(top: 20),
                          child: Text(
                            'Spinning Time:',
                            style: TextStyle(
                              color: Color(0xFF041D57),
                              fontSize: 12,
                              fontFamily: 'Avenir Next LT Pro',
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                        ),
                        // October 1, 2020 - October 30, 2020 from 9 AM to 10 AM
                        Padding(
                          padding: EdgeInsets.only(
                            top: 10,
                            left: 15,
                            right: 15,
                          ),
                          child: Text(
                            spinTime,
                            maxLines: 2,
                            textAlign: TextAlign.center,
                            style: TextStyle(
                              color: Color(0xFF3A3A3A),
                              fontSize: 12,
                              fontFamily: 'Avenir Next LT Pro',
                            ),
                          ),
                        ),
                        Padding(
                          padding: EdgeInsets.only(top: 30),
                          child: Remaining(
                            count: _provider.model?.residueLotteryCount ?? 0,
                          ),
                        ),
                        Padding(
                          padding: EdgeInsets.only(top: 10),
                          child: SpinButton(
                            type: 1,
                            onTap: provider.isCanSpin
                                ? (_isAnimating ? () {} : _spin)
                                : null,
                          ),
                        ),
                        Padding(
                          padding: EdgeInsets.only(top: 10, bottom: 30),
                          child: CandyBalanceButton(
                            count: provider.candyBalance.toInt(),
                            onTap: _candyExchange,
                          ),
                        ),
                      ],
                    ),
                  );
          },
        ),
      ),
    );
  }

  @override
  void dispose() {
    controller.dispose();
    super.dispose();
  }
}
